package com.fm.financemanage.exception;


import com.fm.financemanage.exception.base.AiqaProgramBaseException;
import com.fm.financemanage.response.Callback;
import com.fm.financemanage.constant.ResponseEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.fm.financemanage.response.JsonData;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.Set;


/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@ControllerAdvice
@Component
public class AllExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonData constraintViolationCatch(ConstraintViolationException c) {
        Set<ConstraintViolation<?>> constraintViolations = c.getConstraintViolations();
        String s = constraintViolations.stream().map(ConstraintViolation::getMessageTemplate).reduce((m1, m2) -> m1 + "," + m2).orElse("缺少必要参数");
        return Callback.fail("400", s);
    }

    @ExceptionHandler(AiqaProgramBaseException.class)
    @ResponseBody
    public JsonData dhBaseCatch(AiqaProgramBaseException ex) {
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            return Callback.fail("400", businessException.getMessage());
        }
        return Callback.fail(ResponseEnum.FAIL.getCode(), ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonData exHandler(Exception ex) {
        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex;
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            String s = constraintViolations.stream().map(ConstraintViolation::getMessageTemplate).reduce((m1, m2) -> m1 + "," + m2).orElse("缺少必要参数");
            return Callback.fail("400", s);
        } else if (ex instanceof ParameterException) {
            return Callback.fail("400", ((ParameterException) ex).errorMsg);
        } else if (ex instanceof ArithmeticException) {
            return Callback.fail("505", "算术异常");
        } else if (ex instanceof MethodArgumentTypeMismatchException) {
            return Callback.fail("505", ex.getMessage());
        } else if (ex instanceof IOException) {
            return Callback.fail("505", "io");
        }
        ex.printStackTrace();
        return Callback.fail("800", "网络错误");
    }
}
